﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace Jack.RedisEventBus
{
    internal class DefaultEventStore : IEventStore, IDisposable
    {
        private readonly Dictionary<string, List<Type>> _eventHandlers = new Dictionary<string, List<Type>>(StringComparer.OrdinalIgnoreCase);
        private readonly IServiceProvider _serviceProvider;

        public DefaultEventStore(IServiceProvider serviceProvider)
        {
            _serviceProvider = serviceProvider;
        }

        public Task AttachEventHandle(string eventType, Type eventHandlerType)
        {
            if (_eventHandlers.TryGetValue(eventType, out List<Type> _) == false)
            {
                _eventHandlers[eventType] = new List<Type> { eventHandlerType };
                return Task.CompletedTask;
            }

            _eventHandlers[eventType].Add(eventHandlerType);
            return Task.CompletedTask;
        }

        public void Dispose()
        {
        }

        public Task<List<IEventHandle>> GetEventHandles(string eventType)
        {
            if (_eventHandlers.TryGetValue(eventType, out List<Type> eventHandlerTypes))
            {
                List<IEventHandle> eventHandles = new List<IEventHandle>(eventHandlerTypes.Count);
                foreach (Type eventHandlerType in eventHandlerTypes)
                {
                    IEventHandle eventHandle = _serviceProvider.GetService(eventHandlerType) as IEventHandle;
                    eventHandles.Add(eventHandle);
                }

                return Task.FromResult(eventHandles);
            }

            return Task.FromResult(default(List<IEventHandle>));
        }
    }
}
